// JWT Token工具模块
const jwt = require('jsonwebtoken');
require('dotenv').config();

const JWT_SECRET = process.env.JWT_SECRET || 'campus-express-secret-key-change-in-production';
const JWT_REFRESH_SECRET = process.env.JWT_REFRESH_SECRET || 'campus-express-refresh-secret-key';

/**
 * 生成Access Token（2小时有效期）
 * @param {Object} payload - 包含userId, role等信息
 * @returns {String} JWT Token
 */
function generateAccessToken(payload) {
  const tokenPayload = {
    userId: payload.userId,
    role: payload.role,
    type: 'access'
  };

  return jwt.sign(tokenPayload, JWT_SECRET, {
    expiresIn: '2h', // 2小时
    issuer: 'campus-express',
    audience: 'campus-express-users'
  });
}

/**
 * 生成Refresh Token（7天有效期）
 * @param {Object} payload - 包含userId信息
 * @returns {String} Refresh Token
 */
function generateRefreshToken(payload) {
  const tokenPayload = {
    userId: payload.userId,
    type: 'refresh'
  };

  return jwt.sign(tokenPayload, JWT_REFRESH_SECRET, {
    expiresIn: '7d', // 7天
    issuer: 'campus-express',
    audience: 'campus-express-users'
  });
}

/**
 * 验证Access Token
 * @param {String} token - JWT Token
 * @returns {Object} 解码后的payload，如果无效则返回null
 */
function verifyAccessToken(token) {
  try {
    return jwt.verify(token, JWT_SECRET, {
      issuer: 'campus-express',
      audience: 'campus-express-users'
    });
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      return { expired: true, error: 'Token已过期' };
    } else if (error.name === 'JsonWebTokenError') {
      return { invalid: true, error: 'Token无效' };
    }
    return { error: error.message };
  }
}

/**
 * 验证Refresh Token
 * @param {String} token - Refresh Token
 * @returns {Object} 解码后的payload，如果无效则返回null
 */
function verifyRefreshToken(token) {
  try {
    return jwt.verify(token, JWT_REFRESH_SECRET, {
      issuer: 'campus-express',
      audience: 'campus-express-users'
    });
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      return { expired: true, error: 'Refresh Token已过期' };
    } else if (error.name === 'JsonWebTokenError') {
      return { invalid: true, error: 'Refresh Token无效' };
    }
    return { error: error.message };
  }
}

/**
 * 从请求头中提取Token
 * @param {Object} req - Express请求对象
 * @returns {String|null} Token字符串
 */
function extractTokenFromHeader(req) {
  const authHeader = req.headers.authorization;
  if (!authHeader) {
    return null;
  }

  // 支持 "Bearer <token>" 格式
  const parts = authHeader.split(' ');
  if (parts.length === 2 && parts[0] === 'Bearer') {
    return parts[1];
  }

  return authHeader; // 如果没有Bearer前缀，直接返回整个字符串
}

module.exports = {
  generateAccessToken,
  generateRefreshToken,
  verifyAccessToken,
  verifyRefreshToken,
  extractTokenFromHeader
};

